import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/components/Login.vue'
import Home from '@/components/Home.vue'
import Users from '@/components/user/Users.vue'
import Welcome from '@/components/Welcome.vue'
import Roles from '@/components/right/Roles.vue'
import Rights from '@/components/right/Rights.vue'
import Cate from '@/components/goods/Cate.vue'
import Params from '@/components/goods/Params.vue'
import Goods from '@/components/goods/Goods.vue'
import Add from '@/components/goods/Add.vue'
import Orders from '@/components/order/Orders.vue'
import Reports from '@/components/report/Reports.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: Welcome },
      { path: '/users', component: Users },
      { path: '/roles', component: Roles },
      { path: '/rights', component: Rights },
      { path: '/categories', component: Cate },
      { path: '/params', component: Params },
      { path: '/goods', component: Goods },
      { path: '/goods/add', component: Add },
      { path: '/orders', component: Orders },
      { path: '/reports', component: Reports }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 配置全局前置导航守卫
router.beforeEach((to, from, next) => {
  // 访问 /login 则放行
  if (to.path === '/login') return next()
  // 访问除 /login 之外，需要检查是否携带 token
  const tokenStr = sessionStorage.getItem('token')
  if (!tokenStr) next('/login') // 没有 token，则跳转到login页面
  next() // 携带 token，则放行
})

export default router
